import { createRouter, createWebHistory } from 'vue-router'
import Setting from '@/views/Setting.vue'
import DataStatistics from '@/views/DataStatistics.vue'
import DataDisplay from '@/views/DataDisplay.vue'
import store from '@/store'

const routes = [
  {
    path: '/',
    redirect: '/data-statistics'
  },
  {
    path: '/data-statistics',
    name: 'DataStatistics',
    component: DataStatistics,
    meta: { requiresAuth: true }
  },
  {
    path: '/data-display',
    name: 'DataDisplay',
    component: DataDisplay,
    meta: { requiresAuth: true }
  },
  {
    path: '/setting',
    name: 'Setting',
    component: Setting,
    meta: { requiresAuth: true }
  },
  {
    path: '/control-panel',
    name: 'ControlPanel',
    component: () => import('@/views/ControlPanel.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/data-analysis',
    name: 'DataAnalysis',
    component: () => import('@/views/DataAnalysis.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/about',
    name: 'about',
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !store.getters.isAuthenticated) {
    next({ path: '/login', query: { redirect: to.fullPath } })
  } else if (to.path === '/login' && store.getters.isAuthenticated) {
    next({ path: '/' })
  } else {
    next()
  }
})

export default router
